package com.crm.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.domain.dto.DeptDto;
import com.crm.domain.entity.Dept;
import com.crm.domain.entity.User;
import com.crm.domain.vo.DeptVo;
import com.crm.domain.vo.DeptTreeVo;

import com.crm.mapper.DeptMapper;
import com.crm.mapper.UserManagementMapper;
import com.crm.service.DeptService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept> implements DeptService {
    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private UserManagementMapper userManagementMapper;

    /**
     * 新增部门
     * @param deptDto
     */
    @Override
    public void addDept(DeptDto deptDto) {
        Dept dept = BeanUtil.toBean(deptDto, Dept.class);
        dept.setDeptId(303);
        if (deptDto.getLeader() != null) {
            dept.setLeaderId(Long.valueOf(deptDto.getLeader()));
        }
        deptMapper.insert(dept);
    }

    @Override
    public DeptVo getDept(Integer id) {
        DeptVo deptVo = deptMapper.getDept(id);

        //创建一个列表用于存储所有的父ID
        List<Integer> parentIds = new ArrayList<>();
        parentIds.add(0);
        getParentIds(deptVo.getParentId(), parentIds);
        //将list转成前端需要的String类型
        String ancestors = parentIds.stream()
                .map(String::valueOf) // 将每个Long转换成String
                .collect(Collectors.joining(",")); // 使用逗号连接这些String
        deptVo.setAncestors(ancestors);
        return deptVo;
    }

    /**
     * 查询除了自己子部门以外的其他外
     * @param deptId
     * @return
     */
    @Override
    public List<DeptVo> excludeDept(Integer deptId) {
        List<DeptVo> deptVos = deptMapper.excludeDept(deptId);
        deptVos.forEach(deptVo -> {
            //将list转成前端需要的String类型
            //创建一个列表用于存储所有的父ID
            List<Integer> parentIds = new ArrayList<>();
            //设置祖先
            parentIds.add(0);
            String ancestors = parentIds.stream()
                    .map(String::valueOf) // 将每个Long转换成String
                    .collect(Collectors.joining(",")); // 使用逗号连接这些String
            deptVo.setAncestors(ancestors);
                    });
        return deptVos;
    }

    /**
     *查询所有部门信息
     * @return
     */
    @Override
    public List<DeptVo> listDept(String deptName, Integer status) {
        List<DeptVo> list = deptMapper.list(deptName, status);
        list.forEach(deptVo -> {
            List<User> users = userManagementMapper.selectByDeptIds(deptVo.getDeptId());
            deptVo.setUsers(users);
            //创建一个列表用于存储所有的父ID
            List<Integer> parentIds = new ArrayList<>();
            //设置祖先
            parentIds.add(0);
            //查询所有父部门id的方法
            getParentIds(deptVo.getParentId(), parentIds);
            //将list转成前端需要的String类型
            String ancestors = parentIds.stream()
                    .map(String::valueOf) // 将每个Long转换成String
                    .collect(Collectors.joining(",")); // 使用逗号连接这些String
            deptVo.setAncestors(ancestors);
        });
        return list;
    }

    /**
     * 部门树形选择
     * @return
     */
    @Override
    public List<DeptTreeVo> treeSelectDept() {
        List<DeptTreeVo> list = new ArrayList<>();
        //查询所有部门信息
        List<DeptVo> deptVoList = deptMapper.list(null,null);
        //查询父部门
        Dept dept = deptMapper.selectOne(new QueryWrapper<Dept>()
                .eq("dept_id",100));
        if(null == dept){
            throw new RuntimeException("没有找到根部门");
        }
        //根据父部门，构建部门树形
        DeptTreeVo deptTreeVo = new DeptTreeVo();
        deptTreeVo.setId(dept.getDeptId());
        deptTreeVo.setLabel(dept.getDeptName());

        //构建树形关系
        list.add(deptTreeVo);
        //一级菜单
        List<DeptVo> firstTree = deptVoList.stream().filter(deptVo -> {
            if (deptVo.getParentId().equals(dept.getDeptId())) {
                return true;
            } else {
                return false;
            }
        }).collect(Collectors.toList());
        List<DeptTreeVo> firstTreeList = firstTree.stream().map(d -> {
            DeptTreeVo treeVo = new DeptTreeVo();
            treeVo.setId(d.getDeptId());
            treeVo.setLabel(d.getDeptName());
            return treeVo;
        }).collect(Collectors.toList());
        deptTreeVo.setChildren(firstTreeList);
        //二级菜单
        deptTreeVo.getChildren().stream().map(first -> {
            List<DeptVo> secondTree = deptVoList.stream().filter(deptVo -> {
                if (deptVo.getParentId().equals(first.getId())) {
                    return true;
                } else {
                    return false;
                }
            }).collect(Collectors.toList());

            List<DeptTreeVo> secondTreeList = secondTree.stream().map(second -> {
                DeptTreeVo treeVo = new DeptTreeVo();
                treeVo.setId(second.getDeptId());
                treeVo.setLabel(second.getDeptName());
                return treeVo;
            }).collect(Collectors.toList());
            if (!secondTreeList.isEmpty()){
                first.setChildren(secondTreeList);
            }
            return first;
        }).collect(Collectors.toList());

        return list;
    }

    /**
     * 查询所有父部门id的方法
     * @param parentId
     * @param parentIds
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public List<Integer> getParentIds(Integer parentId, List<Integer> parentIds) {
        //查询父部门
        Dept dept = deptMapper.selectParent(parentId);
        //父部门为空时则返回

        if (null != dept) {
            parentIds.add(dept.getDeptId());
            //递归查询父部门ID
            getParentIds(dept.getParentId(),parentIds);
            //parentIds.addAll(getParentIds(dept.getDeptId(),parentIds));
        }
        return parentIds;
    }

}
